package com.b2c.erp.controller;

import com.alibaba.fastjson.JSON;
import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.DataRow;
import com.b2c.entity.ErpGoodsStockInfoEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.enums.EnumUserActionType;
import com.b2c.entity.vo.ErpOrderReturnItemVo;
import com.b2c.entity.vo.ErpOrderReturnVo;
import com.b2c.interfaces.erp.ErpOrderReturnService;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.erp.DataConfigObject;
import com.b2c.erp.response.ApiResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 描述：
 * 退货订单
 *
 * @author qlp
 * @date 2019-10-15 14:47
 */
@RequestMapping("/order_return")
@Controller
public class OrderReturnController {
    @Autowired
    private ErpOrderReturnService orderReturnService;
    @Autowired
    private ErpUserActionLogService logService;
    private static Logger log = LoggerFactory.getLogger(OrderReturnController.class);

    /***
     * 退货订单list
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String getOrderStockInList(Model model, HttpServletRequest request) {
        Integer pageIndex = 1;
        Integer pageSize = DataConfigObject.getInstance().getPageSize();

        if (StringUtils.isEmpty(request.getParameter("page")) == false) {
            try {
                pageIndex = Integer.parseInt(request.getParameter("page"));
            } catch (Exception e) {
            }
        }


        String refNum = "";
        if (!StringUtils.isEmpty(request.getParameter("refNum"))) {
            refNum = request.getParameter("refNum");
            model.addAttribute("refNum", refNum);
        }
        String orderNum = "";
        if (!StringUtils.isEmpty(request.getParameter("orderNum"))) {
            orderNum = request.getParameter("orderNum");
            model.addAttribute("orderNum", orderNum);
        }
        String logisticsCode = "";
        if (!StringUtils.isEmpty(request.getParameter("logisticsCode"))) {
            logisticsCode = request.getParameter("logisticsCode");
            model.addAttribute("logisticsCode", logisticsCode);
        }

        String refMobile = "";
        if (!StringUtils.isEmpty(request.getParameter("refMobile"))) {
            refMobile = request.getParameter("refMobile");
            model.addAttribute("refMobile", refMobile);
        }

        Integer status=null;
        if (!StringUtils.isEmpty(request.getParameter("status"))) {
            status = Integer.parseInt(request.getParameter("status"));
            model.addAttribute("status", status);
        }

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);

        PagingResponse<ErpOrderReturnVo> result = orderReturnService.getList(pageIndex, pageSize, refNum, orderNum, logisticsCode,refMobile,status);

        model.addAttribute("list", result.getList());
        model.addAttribute("totalSize", result.getTotalSize());

//        List<Long> ids = result.getList().stream().map(o->o.getId()).collect(Collectors.toList());
//        log.info(JSON.toJSONString(ids));

        model.addAttribute("view", "return_order");
        model.addAttribute("pView", "rk");
        model.addAttribute("ejcd", "收货");
        model.addAttribute("sjcd", "订单退货收货");

        return "order_return_list";
    }

    /**
     * @param model
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(Model model, @RequestParam Long id, HttpServletRequest request) {
        model.addAttribute("orderId", id);
        var order = orderReturnService.getById(id);
        model.addAttribute("order", order);

        var itemList = orderReturnService.getItemListById(id);
        model.addAttribute("items", itemList);
        Long in = 0L;
        Long bad = 0L;
        for (ErpOrderReturnItemVo item : itemList) {
            in += item.getInQuantity();
            bad += item.getBadQuantity();
        }
        model.addAttribute("inQuantity", in);
        model.addAttribute("badQuantity", bad);
        return "order_return_print_detail";
    }


    /**
     * 退货订单  合格检验
     *
     * @return
     */
    @RequestMapping(value = "/stock_info_list", method = RequestMethod.GET)
    public String getStockInfo(HttpServletRequest request, Model model) {
        Long id = Long.parseLong(request.getParameter("id"));
        ErpOrderReturnVo stockInfo = orderReturnService.getStockInfo(id);
        if(stockInfo == null) stockInfo = new ErpOrderReturnVo();
        model.addAttribute("lists", stockInfo);
        return "order_return_checkout_stock_info";
    }

    //判断仓位是否正确
    @ResponseBody
    @RequestMapping(value = "/stock_info_check", method = RequestMethod.POST)
    public ApiResult<Integer> checkStockInfo(@RequestBody ErpOrderReturnVo entity, HttpServletRequest request) {
        for (ErpGoodsStockInfoEntity item : entity.getInfos()) {
            Integer id = orderReturnService.checkStockInfo(item.getSpecNumber(), item.getLocationName());
            if (id == -1) return new ApiResult<>(404, "仓位 : " + item.getLocationName() + " 不正确");
        }
        return new ApiResult<>(0, "SUCCESS");
    }

    @ResponseBody
    @RequestMapping(value = "/erp_order_return_cancel", method = RequestMethod.POST)
    public ApiResult<Integer> erp_order_return_cancel(@RequestBody DataRow req, HttpServletRequest request) {
        orderReturnService.erp_order_return_cancel(req.getLong("id"));
        return new ApiResult<>(0, "SUCCESS");
    }

    /**
     * 退货入库
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/upd_stock_info", method = RequestMethod.POST)
    public String stockInfo(HttpServletRequest request) {
//        String[] locationName = request.getParameterValues("locationNumber");
        String[] locationIds = request.getParameterValues("locationId");
//        String[] goodsIds = request.getParameterValues("goodsId");
//        String[] specNumbers = request.getParameterValues("specNumber");
//        String[] specIds = request.getParameterValues("specId");
//        String[] quantities = request.getParameterValues("quantity");
        String[] returnItemIds = request.getParameterValues("returnItemId");
        Integer userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
//        Object trueName = request.getSession().getAttribute("trueName");
        String trueName = request.getSession().getAttribute("trueName") == null ? "" : request.getSession().getAttribute("trueName").toString();
//        String billNo = request.getParameter("billNo");
        Long returnId = Long.parseLong(request.getParameter("returnId"));
        log.info("订单退货入库{returnId:"+returnId+",returnItemIds:"+ JSON.toJSONString(returnItemIds) +",userId:"+userId+",trueName:"+trueName+"}");
        ResultVo<Integer> result = orderReturnService.confirmReceiveAndStockIn(returnId,returnItemIds,locationIds,userId,trueName);

        if (result.getCode() == EnumResultVo.SUCCESS.getIndex()) {

//             orderReturnService.returnOrderStockIn(locationIds, goodsIds, specIds, quantities, itemIds, userId, trueName, billNo, returnId);
            //添加系统日志
            logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.StockOperation,
                    "/order_return/upd_stock_info", "退货合格单入库 ,id :" + returnId + " , 日期 : " + new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()) + "成功数量：" + result, "成功");
            return "redirect:/order_return/list?status=1";
        }else {
            String rurl = request.getRequestURL().toString()+"?id="+returnId;
            return "forward:/paramError?msg=" + result.getMsg()+"&redirect="+rurl;
        }

    }

    /**
     * 退货订单  不良品检验
     *
     * @return
     */
   @RequestMapping(value = "/bad_stock_list", method = RequestMethod.GET)
   public String getBadStock(HttpServletRequest request, Model model) {
       Long id = Long.parseLong(request.getParameter("id"));
       ErpOrderReturnVo stockInfo = orderReturnService.getStockInfo(id);
       if(stockInfo == null )stockInfo = new ErpOrderReturnVo();
       model.addAttribute("lists", stockInfo);
       return "/order_return_checkout_bad_stock";
   }

   /* @ResponseBody
    @RequestMapping(value = "/bad_stock_check", method = RequestMethod.POST)
    public ApiResult<Integer> badStock(@RequestBody ErpOrderReturnVo entity, HttpServletRequest request) {
        for (ErpGoodsStockInfoEntity item : entity.getInfos()) {
            Integer id = orderReturnService.checkBadStock(item.getSpecNumber(), item.getLocationName());
            if (id==-1) return new ApiResult<>(404, "仓位 : "+item.getLocationName() + " 不正确");
        }
        return new ApiResult<>(0, "SUCCESS");
    }*/

    /**
     * 退货订单商品加入不良品
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/upd_bad_stock", method = RequestMethod.POST)
    public String updBadStock(HttpServletRequest request) {
        String[] goodsIds = request.getParameterValues("goodsId");
        String[] specNumbers = request.getParameterValues("specNumber");
        String[] quantities = request.getParameterValues("quantity");
        String[] itemIds = request.getParameterValues("itemId");
        String billNo = request.getParameter("billNo");
        Integer returnId = Integer.parseInt(request.getParameter("returnId"));
        Integer i = orderReturnService.returnOrderStockBadIn(goodsIds, specNumbers, quantities, itemIds, billNo, returnId);
        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.StockOperation,
                "/order_return/upd_bad_stock", "退货不良品单入库 ,id :" + returnId + ", 单据编号 : " + billNo + " , 日期 : " + new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()), "成功");

        return "redirect:/order_return/list";
    }
}
